package com.ice.app.system.role.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.ice.app.system.entity.Role;
import com.ice.app.system.mapper.RoleMapper;
import com.ice.app.system.role.vo.RoleMenuRelVo;
import com.ice.app.system.role.vo.RoleTreeVo;
import com.ice.app.system.role.vo.RoleUserRelVo;
import com.iceframework.core.utils.KeyUtils;
import com.iceframework.core.utils.WebUtils;

/**
 * 
 * 业务逻辑层： 角色
 * 
 * @author Mr.Palo
 * @email 442803840@qq.com
 * 
 */
@Service
public class RoleService {

	@Autowired
	private RoleMapper roleMapper;

	// ----------------------------------------自动生成--------------------------------------------

	/**
	 * 菜单保存
	 * 
	 * @param role
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public boolean saveRole(Role role) throws Exception {
		if (StringUtil.isNotEmpty(role.getRoleId())) {
			// 修改操作
			Role old = this.getRole(role.getRoleId());
			role.setUpdateBy(WebUtils.getUserId());
			role.setUpdateDate(new Date());
			if (old != null) {
				return roleMapper.updateByPrimaryKeySelective(role) > 0;
			}
			return false;
		} else {
			// 保存操作
			String key = KeyUtils.genKey("Role");
			// 顶层角色
			if("0".equals(role.getParentId())) {
				role.setRoleType(1);
			} else {
				role.setRoleType(2);
			}
			role.setRoleId(key);
			role.setCreateBy(WebUtils.getUserId());
			role.setCreateDate(new Date());
			role.setUpdateBy(WebUtils.getUserId());
			role.setUpdateDate(new Date());
			return roleMapper.insertSelective(role) > 0;

		}
	}

	/**
	 * 根据主键删除菜单
	 * 
	 * @param key
	 * @return
	 */
	@Transactional
	public boolean deleteRole(String key) {
		return roleMapper.deleteByPrimaryKey(key) > 0;
	}

	/**
	 * 根据多个主键删除菜单
	 * 
	 * @param keys
	 * @return
	 */
	@Transactional
	public boolean deleteRoles(String keys) {
		if (!StringUtils.isEmpty(keys)) {
			String[] strs = keys.split(",");
			for (String key : strs) {
				this.deleteRole(key);
			}
			return true;
		}
		return false;
	}

	/**
	 * 根据主键获取菜单实体
	 * 
	 * @param key
	 * @return
	 */
	public Role getRole(String key) {
		return roleMapper.selectByPrimaryKey(key);
	}

	/**
	 * 根据给定条件获取菜单实体集合
	 * 
	 * @param key
	 * @return
	 */
	public List<Role> getRoles(Role role) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("role", role);
		return roleMapper.selectByFilter(map);
	}

	// ----------------------------------------自定义（Public）---------------------------------------------

	/**
	 * 获取角色树(数据列表，Bootstrap-table，将数据转换为TreeVo(id,parentId)，无需转换为树状，前端自动转换)
	 * 
	 * @return
	 */
	public List<RoleTreeVo> getRoleTreeList() {
		Map<String, Object> map = new HashMap<>();
		Role role = new Role();
		map.put("role", role);
		// 获取目录
		List<Role> roles = roleMapper.selectByFilter(map);

		List<RoleTreeVo> roleTree = transRoleTreeVo(roles);

		/*
		 * List<RoleTreeVo> trees = new ArrayList<>();
		 * 
		 * if(roleTree!=null) {
		 * trees.addAll(TreeParserUtils.getTreeList(String.valueOf(Constant.RoleType.
		 * ROOT.getValue()), roleTree)); }
		 */
		return roleTree;
	}

	// ----------------------------------------自定义(Private)------------------------------------------
	/**
	 * 转换TreeVo
	 * 
	 * @param roles
	 * @return
	 */
	private List<RoleTreeVo> transRoleTreeVo(List<Role> roles) {
		if (roles != null && roles.size() != 0) {
			List<RoleTreeVo> trees = new ArrayList<>();
			for (Role role : roles) {
				RoleTreeVo roleTreeVo = new RoleTreeVo();
				roleTreeVo.setId(role.getRoleId());
				roleTreeVo.setParentId(role.getParentId());
				roleTreeVo.setRoleName(role.getRoleName());
				roleTreeVo.setRoleType(role.getRoleType());
				roleTreeVo.setStatus(role.getStatus());
				roleTreeVo.setCreateBy(role.getCreateBy());
				roleTreeVo.setCreateDate(role.getCreateDate());
				roleTreeVo.setUpdateBy(role.getUpdateBy());
				roleTreeVo.setUpdateDate(role.getUpdateDate());
				roleTreeVo.setRemark(role.getRemark());
				trees.add(roleTreeVo);
			}
			return trees;
		}
		return null;
	}

	@Transactional
	public boolean saveRoleMenuRel(String roleId, String menuIds) {
		roleMapper.deleteRoleMenuRelByRoleId(roleId);
		String[] split = menuIds.split(",");
		List<RoleMenuRelVo> rels = new ArrayList<RoleMenuRelVo>();
		for (String menuId : split) {
			if (menuId.equals("root")) {
				continue;
			} else if (!menuId.equals("")) {
				RoleMenuRelVo temp = new RoleMenuRelVo();
				temp.setId(KeyUtils.genUUID());
				temp.setMenuId(menuId);
				temp.setRoleId(roleId);
				rels.add(temp);
			}
		}
		boolean result = true;
		for (RoleMenuRelVo record : rels) {
			result = result & roleMapper.insertRoleMenuRelByRoleId(record) > 0;
		}
		return result;
	}

	public List<RoleTreeVo> getMenuTreeByRoleId(String userId) {
		List<RoleTreeVo> role = roleMapper.selectRoleTreeByUserId(userId);
		RoleTreeVo roleTreeVo = new RoleTreeVo();
		roleTreeVo.setName("角色");
		roleTreeVo.setId("0");
		roleTreeVo.setChecked(false);
		role.add(roleTreeVo);
		return role;
	}

	@Transactional
	public boolean saveRoleUserRel(String userId, String roleIds) {
		roleMapper.deleteRoleUserRelByUserId(userId);
		String[] split = roleIds.split(",");
		List<RoleUserRelVo> rels = new ArrayList<RoleUserRelVo>();
		for (String roleId : split) {
			if (roleId.equals("root")) {
				continue;
			} else if (!roleId.equals("")) {
				RoleUserRelVo temp = new RoleUserRelVo();
				temp.setId(KeyUtils.genUUID());
				temp.setRoleId(roleId);
				temp.setUserId(userId);
				rels.add(temp);
			}
		}
		boolean result = true;
		for (RoleUserRelVo record : rels) {
			result = result & roleMapper.insertRoleUserRelByUserId(record) > 0;
		}
		return result;
	}
}